package GsEngine

import (
	"net"
	"strconv"
	"sync"
)

import (
	"GsDB"
	. "tksConfig"
	. "tksLog"
	. "tksStatic"
	. "tksTcp"
	. "tksUint"
)

type TbRole struct {
	Uid  int
	Name string
	Lev  int
	Yb   int
	Yl   int
}

var Roles map[int]*TbRole
var m *sync.Mutex

func init() {
	m = new(sync.Mutex)
	Roles = make(map[int]*TbRole)
}

func sendRsp(conn net.Conn, cmd uint32, from uint32, to uint32, ret Ret, role *TbRole) {
	var rsp LoginGsRsp
	rsp.R = ret
	rsp.Info = role
	data, _ := MsgToBuf(rsp)
	Debug("send rsp, cmd: %d, data: %s", cmd, string(data))
	SendBuffer(conn, cmd, from, to, data)
}

func FindInfoByID(id uint32, info *TokenInfo) error {
	err := GsDB.Cache.GetDataFromRedis(strconv.FormatUint(uint64(id), 10), info)
	if err != nil {
		return err
	}
	return nil
}

func RecvLogin(conn net.Conn, from uint32, to uint32, buf []byte) {
	Debug("recv client login game req from client[%d] ", from)
	var tokenInfo TokenInfo
	var nullRole TbRole
	id, _ := Config.Get("server").Get("id").Int()
	//
	FindInfoByID(from, &tokenInfo)
	if tokenInfo.Uid == 0 {
		sendRsp(conn, CmdLoginGsRsp, uint32(id), from, RetFail, &nullRole)
		return
	}
	r, ok := Roles[tokenInfo.Uid]
	if ok {
		sendRsp(conn, CmdLoginGsRsp, uint32(id), from, RetSucc, r)
		return
	} else {
		sendRsp(conn, CmdLoginGsRsp, uint32(id), from, RetRoleNotExists, &nullRole)
		return
	}
}

func RecvNewRole(conn net.Conn, from uint32, to uint32, buf []byte) {
	var nullRole TbRole
	var tokenInfo TokenInfo
	//
	Debug("recv client new role req from client[%d] ", from)
	id, _ := Config.Get("server").Get("id").Int()
	json, err := BufToMsg(buf)
	if err != nil {
		sendRsp(conn, CmdNewRoleRsp, uint32(id), from, RetMsgFormatError, &nullRole)
		return
	}
	roleName, _ := json.Get("RoleName").String()
	//
	FindInfoByID(from, &tokenInfo)
	if tokenInfo.Uid == 0 {
		sendRsp(conn, CmdNewRoleRsp, uint32(id), from, RetFail, &nullRole)
		return
	}
	r, ok := Roles[tokenInfo.Uid]
	if ok {
		sendRsp(conn, CmdNewRoleRsp, uint32(id), from, RetRoleExists, r)
		return
	} else {
		r = new(TbRole)
		r.Name = roleName
		r.Lev = 0
		r.Uid = tokenInfo.Uid
		r.Yl = 10000
		r.Yb = 10000
		Roles[tokenInfo.Uid] = r
		sendRsp(conn, CmdNewRoleRsp, uint32(id), from, RetSucc, r)
		return
	}
}
